export class WS{
  constructor(host,socketURI) {
    this.hostIp = host.hostIp;
    this.hostPort = host.hostPort;
    this.hostAccountUsername = host.hostAccountUsername;
    this.hostAccountPassword = host.hostAccountPassword;
    this.socketURI = socketURI;
    this.isConnected = false;  //ws对象连接是否成功
  }

  //测试浏览器webSocket的有效性
  isWebSocket(){
    if(window.WebSocket){
      return true;
    }else{
      return false;
    }
  }

  //获取服务端ws服务的地址
  getEndPoint(){
    let protocol = "";
    if(window.location.protocol="http"){
      protocol="ws://";
    }else{
      protocol="wss://";
    }
    return protocol+this.socketURI;
  }

  //发送初始化的连接信息
  sendInitMsg(data){
    data.operate = 'connect';
    this._connection.send(JSON.stringify(data));
  }

  //发送指令
  sendOption(data){
    this._connection.send(JSON.stringify({"operate": "command", "command": data}))
  }

  //初始化连接
  initConnection(options){  //由于当前的js是一个封装,无法调用element-ui中的$message或者借用term输出,为了方便,我们可以通过options将function传入
    //判断浏览器是否支持webSocket
    if(this.isWebSocket()){
      let endpoint = this.getEndPoint();
      this._connection = new WebSocket(endpoint);  //连接建立
    }else{
      options.onError("Websocket not supported!");
      return false;
    }

    this._connection.onopen = function(){
      options.onOpen();
    }

    //从服务器端向前端展示的数据
    this._connection.onmessage = function (evt) {
      let data = evt.data.toString();
      options.onData(data);
    }

    this._connection.onclose = function(evt){
      options.onClose();
    }

    return true;

  }
}
